// Call the dataTables jQuery plugin
$(document).ready(function () {
    $('#dataTable').DataTable();
    $('#dataTable1').DataTable();

    $("#addDepTimePlan").val(moment().format("YYYY-MM-DDTHH:mm"));
    $("#addArrTimePlan").val(moment().format("YYYY-MM-DDTHH:mm"));
    // getTicketTypeInfo(1);

});
var ticketTypeInfo = null;
var workOnFlightID = null;

function getTicketTypeInfo(onFlightID) {
    $.ajax({
        url: ctxPath + "admin/ticketType/" + onFlightID,
        type: 'get',
        dataType: 'json',
        success: function (data) {
            $("#ticketModel").modal('show');
            if (data["result"] == 1) {
                workOnFlightID = onFlightID;
                ticketTypeInfo = data["ticketTypes"];
                console.log(ticketTypeInfo);
                $("#TicketTypeBody").empty();
                for (var ticketType in ticketTypeInfo) {
                    console.log(ticketType)
                    tpl = `<tr id="ticketType${ticketType}">
                                <td>${ticketTypeInfo[ticketType]["ticketTypeID"]}</td>
                                <td width="80px">${$("#addTicketTypeCabin option[value=" + ticketTypeInfo[ticketType]["cabinID"] + "]").text()}</td>
                                <td width="80px">${ticketTypeInfo[ticketType]["basicPrice"]}</td>
                                <td width="70px">${ticketTypeInfo[ticketType]["discount"]}</td>
                                <td width="70px">${ticketTypeInfo[ticketType]["ticketCount"]}</td>
                                <td width="70px">${ticketTypeInfo[ticketType]["remainingTickets"]}</td>
                                <td width="80px">${ticketTypeInfo[ticketType]["luggageLimit"]}</td>
                                <td>${ticketTypeInfo[ticketType]["changeWithdrawalRules"]}</td>
                                <td class="text-center">
                                    <button onclick="modifyTicketType(${ticketType})" class="btn-sm btn-success btn-icon-split">
                                        <span class="icon text-white-50"><i class="fas fa-edit"></i></span>
                                    </button>
                                    <button onclick="deleteTicketType(${ticketTypeInfo[ticketType]["ticketTypeID"]});" class="btn-sm btn-danger btn-icon-split">
                                        <span class="icon text-white-50"><i class="fas fa-trash-alt"></i></span>
                                    </button>
                                </td>
                            </tr>`
                    $("#TicketTypeBody").append(tpl);
                }
                $('#dataTable2').DataTable();
            }
        }
    });
}


// 显示提示框
function showMsg(msg, style, time) {
    style = (style === undefined) ? 'alert-success' : style;
    time = (time === undefined) ? 1200 : time;
    $('.alert').html(msg).addClass(style).show().delay(time).fadeOut();
}

// 添加舱位类型
$("#addCabinBtn").click(function () {
    var tInput = $("#addCabinClass");
    if (tInput.val()) {
        $.ajax({
            url: ctxPath + "admin/addCabin",
            type: 'post',
            data: {"cabinClass": tInput.val()},
            dataType: 'json',
            success: function (data) {
                if (data["result"] == 1) {
                    showMsg("添加成功", 'alert-success');
                    location.reload();
                }
            }
        });
    } else {
        showMsg("名称不可为空", 'alert-warning');
    }
});

// 删除舱位类型
function deleteCabin(cabinID) {
    $.ajax({
        url: ctxPath + "admin/deleteCabin/" + cabinID,
        type: 'get',
        dataType: 'json',
        success: function (data) {
            if (data["result"] == 1) {
                showMsg("删除成功", 'alert-success');
                location.reload();
            }
        }
    });
}

// 修改舱位类型
function modifyCabin(cabinID, btn) {
    modifyName = $("#modifyCabinClass" + cabinID).val();
    console.log(modifyName);
    if (typeof (modifyName) == "undefined") {
        var tmpEl = $("#cabinClass" + cabinID);
        var t = tmpEl.text();
        tmpEl.empty();
        tmpEl.append("<div class='row'>" +
            "           <input id='modifyCabinClass" + cabinID + "' type='text' class='col-8 form-control form-text' placeholder='名称' value='" + t + "'/>" +
            "           <span class='col-1'></span>" +
            "           <span  class='col-2'>" +
            "              <button onclick='location.reload()' class='btn-sm btn-info'><i class='fas fa-times'></i></button>\n" +
            "           </span></div>");
        $('i', $(btn)).attr("class", "fas fa-check");
    } else {
        if (modifyName) {
            $.ajax({
                url: ctxPath + "admin/updateCabin",
                type: 'post',
                data: {"cabinID": cabinID, "cabinClass": modifyName},
                dataType: 'json',
                success: function (data) {
                    if (data["result"] == 1) {
                        showMsg("修改成功", 'alert-success');
                        location.reload();
                    }
                }
            });
        } else {
            showMsg("名称不可为空", 'alert-warning');
        }
    }
}

// 添加执飞航班
$("#addOnFlightBtn").click(function () {
    var executionPrice = $("#addExecutionPrice").val();
    var estimatedTakeoffTime = moment($("#addDepTimePlan").val()).format("YYYY-MM-DD HH:mm:ss");
    var estimatedArrivalTime = moment($("#addArrTimePlan").val()).format("YYYY-MM-DD HH:mm:ss");
    var boardingGate = $("#addGate").val();
    if (executionPrice && estimatedTakeoffTime && estimatedArrivalTime && boardingGate) {
        $.ajax({
            url: ctxPath + "admin/addOnFlight",
            type: 'post',
            data: {
                "flightID": flightID,
                "executionPrice": executionPrice,
                "estimatedTakeoffTime": estimatedTakeoffTime,
                "estimatedArrivalTime": estimatedArrivalTime,
                "boardingGate": boardingGate
            },
            dataType: 'json',
            success: function (data) {
                if (data["result"] == 1) {
                    showMsg("添加成功", 'alert-success');
                    location.reload();
                }
            }
        });
    } else {
        showMsg("录入项不可为空", 'alert-warning');
    }
})

// 删除执飞航班
function deleteOnFlight(onFlightID) {
    $.ajax({
        url: ctxPath + "admin/deleteOnFlight/" + onFlightID,
        type: 'get',
        dataType: 'json',
        success: function (data) {
            if (data["result"] == 1) {
                showMsg("删除成功", 'alert-success');
                location.reload();
            }
        }
    });
}

// 修改执飞航班
function modifyOnFlight(onFlightID, btn) {
    var modifyExecutionPrice = $("#modifyExecutionPrice" + onFlightID).val();
    if (typeof (modifyExecutionPrice) == "undefined") {
        var executionPriceEl = $("#executionPrice" + onFlightID);
        var executionPrice = executionPriceEl.text();
        executionPriceEl.empty();
        executionPriceEl.append("<input id='modifyExecutionPrice" + onFlightID + "' type='number' min='0.00' step='0.01' class='form-control' value='" + executionPrice + "' placeholder='执行价格'>");

        var depTimePlanEl = $("#depTimePlan" + onFlightID);
        var depTimePlan = depTimePlanEl.text();
        depTimePlanEl.empty();
        depTimePlanEl.append("<input id='modifyDepTimePlan" + onFlightID + "' type='datetime-local' value='" + moment(new Date(depTimePlan)).format("YYYY-MM-DDTHH:mm") + "' class='form-control'>");

        var arrTimePlanEl = $("#arrTimePlan" + onFlightID);
        var arrTimePlan = arrTimePlanEl.text();
        arrTimePlanEl.empty();
        arrTimePlanEl.append("<input id='modifyArrTimePlan" + onFlightID + "' type='datetime-local' value='" + moment(new Date(arrTimePlan)).format("YYYY-MM-DDTHH:mm") + "' class='form-control'>");

        var gateEl = $("#gate" + onFlightID);
        var gate = gateEl.text();
        gateEl.empty();
        gateEl.append("<div class='row'>" +
            "           <input id='modifyGate" + onFlightID + "' type='text' class='col-8 form-control' value='" + gate + "' placeholder='登机口'>" +
            "           <span class='col-1'></span>" +
            "           <span  class='col-2'>" +
            "              <button onclick='location.reload()' class='btn-sm btn-info'><i class='fas fa-times'></i></button>\n" +
            "           </span></div>");

        $('i', $(btn)).attr("class", "fas fa-check");
    } else {
        // var modifyExecutionPrice = $("#modifyExecutionPrice"+onFlightID).val();
        var modifyDepTimePlan = moment($("#modifyDepTimePlan" + onFlightID).val()).format("YYYY-MM-DD HH:mm:ss");
        var modifyArrTimePlan = moment($("#modifyArrTimePlan" + onFlightID).val()).format("YYYY-MM-DD HH:mm:ss");
        var modifyGate = $("#modifyGate" + onFlightID).val();
        if (modifyExecutionPrice && modifyGate && modifyDepTimePlan && modifyArrTimePlan) {
            $.ajax({
                url: ctxPath + "admin/updateOnFlight",
                type: 'post',
                data: {
                    "onFlightID": onFlightID,
                    "executionPrice": modifyExecutionPrice,
                    "estimatedTakeoffTime": modifyDepTimePlan,
                    "estimatedArrivalTime": modifyArrTimePlan,
                    "boardingGate": modifyGate
                },
                dataType: 'json',
                success: function (data) {
                    if (data["result"] == 1) {
                        showMsg("修改成功", 'alert-success');
                        location.reload();
                    }
                }
            });
        } else {
            showMsg("修改项不可为空", 'alert-warning');
        }
    }
}
// 添加机机票类型
$("#addTicketTypeBtn").click(function () {
    var ticketTypeCabin = $("#addTicketTypeCabin").val();
    var ticketTypePrice = $("#addTicketTypePrice").val();
    var ticketTypeDisCount = $("#addTicketTypeDisCount").val();
    var ticketTypeCount = $("#addTicketTypeCount").val();
    var ticketTypeRemaining = $("#addTicketTypeRemaining").val();
    var ticketTypeLuggageLimit = $("#addTicketTypeLuggageLimit").val();
    var ticketTypeRule = $("#addTicketTypeRule").val();
    if (ticketTypePrice && ticketTypeDisCount && ticketTypeCount && ticketTypeRemaining && ticketTypeLuggageLimit) {
        $.ajax({
            url: ctxPath + "admin/addTicketType",
            type: 'post',
            data: {
                "onFlightID": workOnFlightID,
                "cabinID": ticketTypeCabin,
                "basicPrice": ticketTypePrice,
                "discount": ticketTypeDisCount,
                "ticketCount": ticketTypeCount,
                "remainingTickets": ticketTypeRemaining,
                "luggageLimit": ticketTypeLuggageLimit,
                "changeWithdrawalRules": ticketTypeRule
            },
            dataType: 'json',
            success: function (data) {
                if (data["result"] == 1) {
                    showMsg("添加成功", 'alert-success');
                    getTicketTypeInfo(workOnFlightID);
                }
            }
        });
    } else {
        showMsg("录入项不可为空", 'alert-warning');
    }
})

// 删除机票类型
function deleteTicketType(typeID) {
    $.ajax({
        url: ctxPath + "admin/deleteTicketType/" + typeID,
        type: 'get',
        dataType: 'json',
        success: function (data) {
            if (data["result"] == 1) {
                showMsg("删除成功", 'alert-success');
                getTicketTypeInfo(workOnFlightID);
            }
        }
    });
}


// 修改机票类型
function modifyTicketType(index, btn) {
    $("#ticketType"+index).empty();
    $("#ticketType"+index).append(
        `<th></th>
        <th width="80px">
            <select id="TicketTypeCabin${index}" class="form-control">
                ${$("#addTicketTypeCabin").html()}
            </select>
        </th>
        <th width="80px"><input id="modifyTicketTypePrice${index}" value="${ticketTypeInfo[index]["basicPrice"]}" type="number" min="0.00" step="0.01" class="form-control" placeholder="销售价格"/></th>
        <th width="70px"><input id="modifyTicketTypeDisCount${index}" value="${ticketTypeInfo[index]["discount"]}" type="number" min="0.00" step="0.01" class="form-control" placeholder="折扣"/></th>
        <th width="70px"><input id="modifyTicketTypeCount${index}" value="${ticketTypeInfo[index]["ticketCount"]}" type="number" min="0" step="1" class="form-control" placeholder="总数"/></th>
        <th width="70px"><input id="modifyTicketTypeRemaining${index}" value="${ticketTypeInfo[index]["remainingTickets"]}" type="number" min="0" step="1" class="form-control" placeholder="余量"/></th>
        <th width="80px"><input id="modifyTicketTypeLuggageLimit${index}" value="${ticketTypeInfo[index]["luggageLimit"]}" type="number" min="0.00" step="0.01" class="form-control" placeholder="行李限重"/></th>
        <th><textarea id="modifyTicketTypeRule${index}" type="text" class="form-control" placeholder="改退签规则">${ticketTypeInfo[index]["changeWithdrawalRules"]}</textarea></th>
        <th class="text-center">
            <button id="modifyTicketTypeBtn${index}" class="btn-sm btn-success btn-icon-split">
                <span class="icon text-white-50"><i class="fas fa-check"></i></span>
            </button>
            <button onclick="location.reload();" class="btn-sm btn-primary btn-icon-split">
                <span class="icon text-white-50"><i class="fas fa-times"></i></span>
            </button>
        </th>`
    );
    $("#modifyTicketTypeBtn"+index).click(function () {
        var ticketTypeCabin = $("#TicketTypeCabin"+index).val();
        var ticketTypePrice = $("#modifyTicketTypePrice"+index).val();
        var ticketTypeDisCount = $("#modifyTicketTypeDisCount"+index).val();
        var ticketTypeCount = $("#modifyTicketTypeCount"+index).val();
        var ticketTypeRemaining = $("#modifyTicketTypeRemaining"+index).val();
        var ticketTypeLuggageLimit = $("#modifyTicketTypeLuggageLimit"+index).val();
        var ticketTypeRule = $("#modifyTicketTypeRule"+index).val();
        if (ticketTypePrice && ticketTypeDisCount && ticketTypeCount && ticketTypeRemaining && ticketTypeLuggageLimit) {
            $.ajax({
                url: ctxPath + "admin/updateTicketType",
                type: 'post',
                data: {
                    "ticketTypeID": ticketTypeInfo[index]["ticketTypeID"],
                    "onFlightID": workOnFlightID,
                    "cabinID": ticketTypeCabin,
                    "basicPrice": ticketTypePrice,
                    "discount": ticketTypeDisCount,
                    "ticketCount": ticketTypeCount,
                    "remainingTickets": ticketTypeRemaining,
                    "luggageLimit": ticketTypeLuggageLimit,
                    "changeWithdrawalRules": ticketTypeRule
                },
                dataType: 'json',
                success: function (data) {
                    if (data["result"] == 1) {
                        showMsg("修改成功", 'alert-success');
                        getTicketTypeInfo(workOnFlightID);
                    }
                }
            });
        } else {
            showMsg("修改项不可为空", 'alert-warning');
        }
    });
}